#include <tidy.h>
#include <tidybuffio.h>

#include "QHtmlTidy.h"

QHtmlTidy::QHtmlTidy()
{
    m_tdoc = tidyCreate();
    tidyOptSetBool(m_tdoc, TidyXmlDecl, yes);
    tidyOptSetBool(m_tdoc, TidyXmlOut, yes);
    tidyOptSetBool(m_tdoc, TidyForceOutput, yes);

    tidyOptSetBool(m_tdoc, TidyIndentAttributes, no);
    tidyOptSetBool(m_tdoc, TidyIndentContent, no);
    tidyOptSetInt(m_tdoc, TidyNewline, 0);
    tidyOptSetInt(m_tdoc, TidyWrapLen, 0);
    tidyOptSetBool(m_tdoc, TidyMark, no);

    tidyOptSetBool(m_tdoc, TidyShowWarnings, no);
    tidyOptSetBool(m_tdoc, TidyShowInfo, no);
    tidyOptSetBool(m_tdoc, TidyQuiet, yes);

}

QHtmlTidy::~QHtmlTidy()
{
    tidyRelease(m_tdoc);
}

QByteArray QHtmlTidy::parse(const QByteArray &html)
{
    QByteArray xml;
    int rc;
    rc = tidyParseString(m_tdoc, html.data());           // Parse the input
    if ( rc >= 0 )
        rc = tidyCleanAndRepair(m_tdoc);               // Tidy it up!
    if ( rc >= 0 )
        rc = tidyRunDiagnostics(m_tdoc);
    if ( rc >= 0 ) {
        TidyBuffer m_output = {0, 0, 0, 0, 0};
        rc = tidySaveBuffer(m_tdoc, &m_output);
        xml = QByteArray(reinterpret_cast<char*>(m_output.bp), m_output.size);
        tidyBufFree(&m_output);
    }
    return xml;
}
